package com.fujimana.rockincat.restree.phase;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.fujimana.rockincat.restree.exception.HttpException;
import com.fujimana.rockincat.restree.util.IOUtils;
import com.fujimana.rockincat.restree.util.HttpUtils.HttpStatusCode;

public class RenderingResponsePhase implements Phase {

	@Override
	public void execute(Map<String, Object> context) {
		HttpServletResponse response = (HttpServletResponse) context
				.get(HttpServletResponse.class.getName());

		byte[] ret = (byte[]) context.get("return");
		
		if(ret == null) {
			return;
		}

		ServletOutputStream os = null;
		try {
			os = response.getOutputStream();
			os.write(ret);

		} catch (IOException e) {
			throw new HttpException(HttpStatusCode.INTERNAL_SERVER_ERROR);
		} finally {
			IOUtils.close(os);
		}
	}

	@Override
	public String getId() {
		return RenderingResponsePhase.class.getSimpleName();
	}

	@Override
	public boolean isChain() {
		return true;
	}
}
